package com.szh.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConstants;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.szh.domain.OrderInfo;
import com.szh.domain.RefundInfo;
import com.szh.enums.AliPayTradeState;
import com.szh.enums.OrderStatus;
import com.szh.enums.PayType;
import com.szh.service.AliPayService;
import com.szh.service.OrderInfoService;
import com.szh.service.PaymentInfoService;
import com.szh.service.RefundInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 */
@Service
public class AliPayServiceImpl implements AliPayService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AliPayServiceImpl.class);

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private RefundInfoService refundInfoService;

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private Environment environment;

    private final Lock lock = new ReentrantLock();

    /**
     * 调用支付宝的统一收单下单并支付页面接口
     * @param productId 商品id
     * @return html形式的form表单，包含自动提交的脚本
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,
                   isolation = Isolation.REPEATABLE_READ,
                   rollbackFor = Exception.class)
    public String tradeCreate(Long productId) {
        try {
            LOGGER.info("生成订单");
            OrderInfo orderInfo = orderInfoService.createOrderByProductId(productId, PayType.ALIPAY.getType());
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            //支付完成后，支付宝向我们的系统发起异步通知的地址
            request.setNotifyUrl(environment.getProperty("alipay.notify-url"));
            //支付完成后，我们想让页面跳转回到自己系统的页面，配置returnUrl
            request.setReturnUrl(environment.getProperty("alipay.return-url"));
            //组装当前业务方法必需的请求参数
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderInfo.getOrderNo());
            BigDecimal totalAmount = new BigDecimal(orderInfo.getTotalFee().toString()).divide(new BigDecimal("100"));
            bizContent.put("total_amount", totalAmount);
            bizContent.put("subject", orderInfo.getTitle());
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
            LOGGER.info("请求参数 ===> {}", bizContent.toString());
            request.setBizContent(bizContent.toString());
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            if (response.isSuccess()) {
                LOGGER.info("调用成功，返回结果 ===> {}", response.getBody());
                return response.getBody();
            } else {
                LOGGER.info("调用失败，返回码 ===> " + response.getCode() + ", 返回描述 ===> " + response.getMsg());
                throw new RuntimeException("创建支付交易失败");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException("创建支付交易失败");
        }
    }

    /**
     * 支付完成之后的异步通知，支付宝会根据API中我们设置的 notify_url，通过 POST 请求的形式将支付结果作为参数通知给我们
     * @param params 通知参数
     * @return 支付结果
     */
    @Override
    public String tradeNotify(Map<String, String> params) {
        String result = "failure";
        try {
            boolean signVerified = AlipaySignature.rsaCertCheckV1(
                    params,
                    environment.getProperty("alipay.alipay-public-key"),
                    AlipayConstants.CHARSET_UTF8,
                    AlipayConstants.SIGN_TYPE_RSA2);
            //验签失败则记录异常日志，并在response中返回failure
            if (!signVerified) {
                LOGGER.error("支付成功异步通知验签失败！");
                return result;
            }
            //验签成功
            LOGGER.info("支付成功异步通知验签成功！");
            //按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验
            //1.商户需要验证该通知数据中的 out_trade_no 是否为商户系统中创建的订单号
            String outTradeNo = params.get("out_trade_no");
            OrderInfo orderInfo = orderInfoService.getOrderByOrderNo(outTradeNo);
            if (null == orderInfo) {
                LOGGER.error("校验失败，订单不存在");
                return result;
            }
            //2.判断 total_amount 是否确实为该订单的实际金额（即商户订单创建时的金额）
            String totalAmount = params.get("total_amount");
            BigDecimal totalAmount1 = new BigDecimal(totalAmount).multiply(new BigDecimal("100"));
            BigDecimal totalAmount2 = new BigDecimal(orderInfo.getTotalFee().toString());
            if (totalAmount1.compareTo(totalAmount2) != 0) {
                LOGGER.error("校验失败，金额不匹配");
                return result;
            }
            //3.校验通知中的 seller_id（或者 seller_email) 是否为 out_trade_no 这笔单据的对应的操作方
            String sellerId = params.get("seller_id");
            String sellerIdProperty = environment.getProperty("alipay.seller-id");
            if (!sellerId.equals(sellerIdProperty)) {
                LOGGER.error("校验失败，卖家支付宝账号不匹配");
                return result;
            }
            //4.验证 app_id 是否为该商户本身
            String appId = params.get("app_id");
            String appIdProperty = environment.getProperty("alipay.app-id");
            if (!appId.equals(appIdProperty)) {
                LOGGER.error("校验失败，支付宝应用APPID不匹配");
                return result;
            }
            //5.在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS 时，才会认定为买家付款成功
            String tradeStatus = params.get("trade_status");
            if (!"TRADE_SUCCESS".equals(tradeStatus)) {
                LOGGER.error("校验失败，交易状态不匹配");
                return result;
            }
            //代码走到这里，则说明二次校验成功，处理业务，修改订单状态，记录支付日志
            this.processOrder(params);
            //校验成功后在response中返回success并继续商户自身业务处理
            result = "success";
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 处理业务，修改订单状态，记录支付日志
     * @param params 通知参数
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,
                   isolation = Isolation.REPEATABLE_READ,
                   rollbackFor = Exception.class)
    public void processOrder(Map<String, String> params) {
        LOGGER.info("处理订单");
        //获取订单号
        String orderNo = params.get("out_trade_no");
        if (lock.tryLock()) {
            try {
                //处理重复通知，接口调用的幂等性：无论接口被调用多少次，以下业务仅执行一次
                //如果订单状态不是未支付，则直接返回
                String orderStatus = orderInfoService.queryOrderStatus(orderNo);
                if (!OrderStatus.NOTPAY.getType().equals(orderStatus)) {
                    return;
                }
                //更新订单状态
                orderInfoService.updateStatusByOrderNo(orderNo, OrderStatus.SUCCESS);
                //记录支付日志
                paymentInfoService.createPaymentInfo(params);
            } finally {
                lock.unlock();
            }
        }
    }

    /**
     * 取消订单，调用支付宝统一收单交易关闭接口
     * @param orderNo 订单号
     */
    @Override
    public void cancelOrder(String orderNo) {
        //调用支付宝提供的统一收单交易关闭接口
        this.closeOrder(orderNo);
        //更新用户订单状态
        orderInfoService.updateStatusByOrderNo(orderNo, OrderStatus.CANCEL);
        //更新支付记录的状态为已关闭
        paymentInfoService.updateStatusByOrderNo(orderNo, AliPayTradeState.CLOSED);
    }

    /**
     * 支付宝提供的统一收单交易关闭接口
     * @param orderNo 订单号
     */
    private void closeOrder(String orderNo) {
        try {
            LOGGER.info("统一收单交易关闭接口的调用，订单号 ===> {}", orderNo);
            AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderNo);
            request.setBizContent(bizContent.toString());
            AlipayTradeCloseResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                LOGGER.info("调用成功，返回结果 ===> {}", response.getBody());
            } else {
                LOGGER.info("调用失败，返回码 ===> " + response.getCode() + ", 返回描述 ===> " + response.getMsg());
            }
        } catch (AlipayApiException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 查询订单，调用支付宝统一收单交易查询接口
     * @param orderNo 订单号
     * @return String
     */
    @Override
    public String queryOrder(String orderNo) {
        try {
            LOGGER.info("统一收单交易查询接口的调用，订单号 ===> {}", orderNo);
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderNo);
            request.setBizContent(bizContent.toString());
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                LOGGER.info("调用成功，返回结果 ===> " + response.getBody());
                return response.getBody();
            } else {
                LOGGER.info("调用失败，返回码 ===> " + response.getCode() + ", 返回描述 ===> " + response.getMsg());
                return null; //订单不存在
            }
        } catch (AlipayApiException ex) {
            ex.printStackTrace();
            throw new RuntimeException("查询订单失败");
        }
    }

    /**
     * 申请退单退款，调用支付宝统一收单交易退款接口
     * @param orderNo 订单号
     * @param reason 退款原因
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,
                   isolation = Isolation.REPEATABLE_READ,
                   rollbackFor = Exception.class)
    public void refund(String orderNo, String reason) {
        try {
            LOGGER.info("统一收单交易退款接口的调用，订单号 ===> {}，退款原因 ===> {}", orderNo, reason);
            //创建退款单
            RefundInfo refundInfo = refundInfoService.createRefundByOrderNo(orderNo, reason);
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderNo);
            BigDecimal refundAmount = new BigDecimal(refundInfo.getRefund().toString())
                    .divide(new BigDecimal("100"));
            bizContent.put("refund_amount", refundAmount);
            bizContent.put("refund_reason", reason);
            request.setBizContent(bizContent.toString());
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            if (response.isSuccess()) { //退款成功
                LOGGER.info("调用成功，返回结果 ===> {}", response.getBody());
                //更新订单状态
                orderInfoService.updateStatusByOrderNo(orderNo, OrderStatus.REFUND_SUCCESS);
                //更新退款单
                refundInfoService.updateRefundForAliPay(refundInfo.getRefundNo(),
                        response.getBody(), AliPayTradeState.REFUND_SUCCESS.getType());
            } else { //退款失败
                LOGGER.info("调用失败，返回码 ===> " + response.getCode() + ", 返回描述 ===> " + response.getMsg());
                //更新订单状态
                orderInfoService.updateStatusByOrderNo(orderNo, OrderStatus.REFUND_ABNORMAL);
                //更新退款单
                refundInfoService.updateRefundForAliPay(refundInfo.getRefundNo(),
                        response.getBody(), AliPayTradeState.REFUND_ERROR.getType());
            }
        } catch (AlipayApiException ex) {
            ex.printStackTrace();
            throw new RuntimeException("创建退款申请失败");
        }
    }

    /**
     * 查询退款，调用支付宝统一收单交易退款查询接口
     * @param orderNo 订单号
     */
    @Override
    public String queryRefund(String orderNo) {
        try {
            LOGGER.info("统一收单交易退款查询接口的调用，订单号 ===> {}", orderNo);
            AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderNo);
            bizContent.put("out_request_no", orderNo);
            request.setBizContent(bizContent.toString());
            AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                LOGGER.info("调用成功，返回结果 ===> " + response.getBody());
                return response.getBody();
            } else {
                LOGGER.info("调用失败，返回码 ===> " + response.getCode() + ", 返回描述 ===> " + response.getMsg());
                return null;
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException("查单接口的调用失败");
        }
    }

    /**
     * 根据账单类型和日期获取账单url地址，调用支付宝查询对账单下载地址接口
     * @param billDate 账单日期
     * @param type 账单类型
     */
    @Override
    public String queryTradeBill(String billDate, String type) {
        try {
            LOGGER.info("查询对账单下载地址接口的调用，日期 ===> {}，账单类型 ===> {}", billDate, type);
            AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("bill_date", billDate);
            bizContent.put("bill_type", type);
            request.setBizContent(bizContent.toString());
            AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                LOGGER.info("调用成功，返回结果 ===> " + response.getBody());
                Gson gson = new Gson();
                Map<String, Map<String, String>> result = gson.fromJson(response.getBody(), Map.class);
                Map<String, String> billDownloadUrlResponse = result.get("alipay_data_dataservice_bill_downloadurl_query_response");
                return billDownloadUrlResponse.get("bill_download_url");
            } else {
                LOGGER.info("调用失败，返回码 ===> " + response.getCode() + ", 返回描述 ===> " + response.getMsg());
                throw new RuntimeException("申请账单失败");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException("申请账单url失败");
        }
    }

    /**
     * 根据订单号调用支付宝查单接口，核实订单状态
     * 如果订单未创建，则更新商户端订单状态
     * 如果订单未支付，则调用关单接口关闭订单，并更新商户端订单状态
     * 如果订单已支付，则更新商户端订单状态，并记录支付日志
     * @param orderNo 订单号
     */
    @Override
    public void checkOrderStatus(String orderNo) {
        LOGGER.warn("根据订单号核实订单状态 ===> {}", orderNo);
        String result = this.queryOrder(orderNo);
        //如果订单未创建，则更新商户端订单状态
        if (StringUtils.isEmpty(result)) {
            LOGGER.warn("核实订单未创建 ===> {}", orderNo);
            //更新商户端订单状态
            orderInfoService.updateStatusByOrderNo(orderNo, OrderStatus.CLOSED);
        } else {
            //解析查单响应结果
            Gson gson = new Gson();
            HashMap<String, LinkedTreeMap> resultMap = gson.fromJson(result, HashMap.class);
            LinkedTreeMap alipayTradeQueryResponse = resultMap.get("alipay_trade_query_response");
            String tradeStatus = (String) alipayTradeQueryResponse.get("trade_status");
            //如果订单未支付，则调用关单接口关闭订单，并更新商户端订单状态
            if (AliPayTradeState.NOTPAY.getType().equals(tradeStatus)) {
                LOGGER.warn("核实订单未支付 ===> {}", orderNo);
                //如果订单未支付，则调用关单接口关闭订单
                this.closeOrder(orderNo);
                //更新商户端订单状态
                orderInfoService.updateStatusByOrderNo(orderNo, OrderStatus.CLOSED);
            }
            //如果订单已支付，则更新商户端订单状态，并记录支付日志
            if (AliPayTradeState.SUCCESS.getType().equals(tradeStatus)) {
                LOGGER.warn("核实订单已支付 ===> {}", orderNo);
                //如果订单已支付，则更新商户端订单状态
                orderInfoService.updateStatusByOrderNo(orderNo, OrderStatus.SUCCESS);
                //将其记录到支付日志中
                paymentInfoService.createPaymentInfo(alipayTradeQueryResponse);
            }
        }
    }
}
